package cn.xdf.demo01;

import cn.xdf.dao.GoodsDao;
import cn.xdf.entity.Goods;
import org.apache.lucene.document.*;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.index.IndexWriterConfig;
import org.apache.lucene.index.Term;
import org.apache.lucene.search.TermQuery;
import org.apache.lucene.store.FSDirectory;
import org.apache.lucene.util.Version;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.wltea.analyzer.lucene.IKAnalyzer;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class Demo03_增删改 {

    //创建ik分析器-分词器
    IKAnalyzer analyzer=new IKAnalyzer();

    //索引库配置对象
    IndexWriterConfig config=new IndexWriterConfig(Version.LUCENE_4_10_3,analyzer);

    /**
     *  设置索引库打开方式
     *  APPEND:每次执行都会将本次产生的数据追加到索引库
     *  CREATE:每次运行前会清空索引库，每次执行都会将本次产生的数据追加到索引库,每次运行前都会清空
     *  CREATE_OR_APPEND:如果有索引库就追加，如果没有就创建
     */


    //创建索引库目录对象，指定索引库目录,存在磁盘
    FSDirectory dir = FSDirectory.open(new File("D:/aaa/index"));

    //创建索引库操作对象
    IndexWriter indexWriter=new IndexWriter(dir,config);

    public Demo03_增删改() throws IOException {
    }


    @Before
    public  void before()throws Exception{

        config.setOpenMode(IndexWriterConfig.OpenMode.CREATE);
    }


    @After
    public void after()throws Exception{
        //提交事务
        indexWriter.commit();
        indexWriter.commit();
        dir.close();
    }

    @Test//删
    public void test01() throws IOException {

//        //添加索引
//        indexWriter.addDocuments(docList);
        TermQuery termQuery = new TermQuery(new Term("title", "游戏"));
        indexWriter.deleteDocuments(termQuery);
    }

    @Test//改
    public void test02() throws IOException {

        Term term = new Term("title", "游戏");


        Document doc=new Document();
        //添加域对象
        doc.add(new StringField("id","888", Field.Store.YES));
        doc.add(new TextField("name","很好的手机啊", Field.Store.YES));
        doc.add(new TextField("title","真的非常好用的手机", Field.Store.YES));
        doc.add(new DoubleField("price",99999.9D, Field.Store.YES));
        doc.add(new StoredField("pic","http://"));//一定会存，所以没后面参数,存到索引库

        //根据条件先把符合条件记录全部删除，然后再新增一片文档
        indexWriter.updateDocument(term,doc);
    }


}
